<template>
  <div class="root-table">
    <div class="table-operations">
      <a-button @click="onAdd">添加</a-button>
      <a-button @click="onAdds">批量添加</a-button>
      <a-button @click="onDels">批量删除</a-button>
      <a-button @click="onRefresh">刷新</a-button>
      <a-row type="flex">
        <a-col :span="6" :order="4" class="a-col">
          <a-input-search placeholder="请输入名称"  @search="onSearchName"/>
        </a-col>
        <a-col :span="6" :order="3" class="a-col">
          <a-tree-select
            showSearch
            allowClear
            :treeNodeFilterProp="'title'"
            style="width:100%"
            :treeData="treeData"
            :value="classifyIds"
            @change="onChangeCategoryTree"
            :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
            :showCheckedStrategy="SHOW_PARENT"
            placeholder="请选择图库分类"
          />
        </a-col>
        <a-col :span="6" :order="2" class="a-col"></a-col>
        <a-col :span="6" :order="1" class="a-col"></a-col>
      </a-row>
    </div>
    <a-table :columns="columns"
      :rowKey="record => record.id"
      :dataSource="data"
      :pagination="pagination"
      :loading="loading"
      @change="handleTableChange"
      :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
    >
      <template slot="url" slot-scope="url">
        <img class="record-picture" :src="url"/>
      </template>
      <template slot="onlySearch" slot-scope="onlySearch">
        {{onlySearch?'yes':'no'}}
      </template>
      <template slot="category" slot-scope="id">
        {{getImageStorageAndClassifyList(id)}}
      </template>
      <template slot="operation" slot-scope="text, record">
        <a @click="onEdit(record)" href="javascript:;">编辑</a>
        <a @click="onDelete(record.id)" href="javascript:;">删除</a>
      </template>
    </a-table>
    <keep-alive>
    <image-store-add-batch
      ref="collectionFormForBatch"
      :title="title"
      :visible="visibleForBatch"
      :confirmLoading="confirmLoadingForBatch"
      :data="record"
      @ok="handleOkForBatch"
      @cancel="handleCancelForBatch"/>
    </keep-alive>
    <keep-alive>
    <image-store-add
      ref="collectionForm"
      :title="title"
      :visible="visible"
      :confirmLoading="confirmLoading"
      :data="record"
      @ok="handleOk"
      @cancel="handleCancel"/>
    </keep-alive>
  </div>
</template>
<script>
import Vue from 'vue'
import serv from './ImageStoreService'
import imageStoreAdd from './ImageStoreAdd'
import ImageStoreAddBatch from './ImageStoreAddBatch'
import { TreeSelect, Button, Table, Col, Row, Input } from 'ant-design-vue'
const SHOW_PARENT = TreeSelect.SHOW_PARENT
Vue.component(Input.Search.name, Input.Search)
Vue.component(Row.name, Row)
Vue.component(Col.name, Col)
Vue.component(Table.name, Table)
Vue.component(Button.name, Button)

const columns = [{
  title: '名称',
  sorter: false,
  dataIndex: 'name',
  width: '10%'
}, {
  title: '图',
  dataIndex: 'url',
  width: '10%',
  scopedSlots: { customRender: 'url' }
}, {
  title: '标签',
  dataIndex: 'tag',
  width: '20%'
}, {
  title: '图片签名',
  dataIndex: 'contSign'
}, {
  title: '图库分类',
  dataIndex: 'imageStorageClassifyNames',
  width: '10%'
}, {
  title: '只可以图搜索',
  dataIndex: 'onlySearch',
  scopedSlots: { customRender: 'onlySearch' }
}, {
  title: '创建时间',
  dataIndex: 'createTime'
}, {
  title: 'operation',
  dataIndex: '',
  scopedSlots: { customRender: 'operation' }
}]

export default {
  components: {
    imageStoreAdd, ImageStoreAddBatch
  },
  mounted () {
    this.getTree()
    this.fetch({
      size: this.pagination.pageSize,
      page: this.pagination.current
    })
  },
  computed: {
    classifyIds: function () {
      return this.searchData.classifyId ? this.searchData.classifyId : []
    },
    name: function () {
      return this.searchData.name
    }
  },
  data () {
    return {
      data: [],
      pagination: {
        pageSize: 5,
        current: 1
      },
      selectedRowKeys: [],
      loading: false,
      columns,
      page: {},

      title: '',
      visible: false,
      confirmLoading: false,
      record: {},

      visibleForBatch: false,
      confirmLoadingForBatch: false,

      treeData: [],
      SHOW_PARENT,

      searchData: {}
    }
  },
  methods: {
    onAdd () {
      this.title = '添加图片'
      this.visible = true
      this.confirmLoading = false
    },
    onAdds () {
      this.title = '批量添加图片'
      this.visibleForBatch = true
      this.confirmLoadingForBatch = false
    },
    onDelete (id) {
      const _this = this
      this.$confirm({
        title: '友情提示',
        content: '要删除这个图吗',
        onOk () {
          return new Promise((resolve, reject) => {
            serv.delete(id).then(res => {
              if (res.data.code === 0) {
                const dataSource = [..._this.data]
                _this.data = dataSource.filter(item => item.id !== id)
                resolve()
              } else {
                _this.$message.error(res.data.msg)
                resolve()
              }
            })
          }).catch(() => console.log('Oops errors!'))
        },
        onCancel () {}
      })
    },
    onEdit (record) {
      this.title = '编辑图片'
      this.visible = true
      this.confirmLoading = false
      this.record = record
    },
    onDels () {
      const _this = this
      this.$confirm({
        title: '友情提示',
        content: '要删除这些图吗',
        onOk () {
          return new Promise((resolve, reject) => {
            let formData = new FormData()
            formData.append('ids[]', _this.selectedRowKeys)
            serv.deleteForBatch(formData).then(res => {
              if (res.data.code === 0) {
                const dataSource = [..._this.data]
                _this.data = dataSource.filter(item => !_this.selectedRowKeys.includes(item.id))
                resolve()
              } else {
                _this.$message.error(res.data.msg)
                resolve()
              }
            })
          }).catch(() => console.log('Oops errors!'))
        },
        onCancel () {}
      })
    },
    onRefresh () {
      this.pagination.current = 1
      // this.searchData = {}
      this.fetch({
        size: this.pagination.pageSize,
        page: this.pagination.current
      })
    },
    onSearchName (value) {
      this.pagination.current = 1
      if (value) {
        this.searchData.name = value
      } else {
        delete this.searchData.name
      }
      this.searchData = {...this.searchData}
      this.fetch({
        size: this.pagination.pageSize,
        page: this.pagination.current,
        ...this.searchData
      })
    },
    handleOk (classifyIds) {
      const form = this.$refs.collectionForm.form
      form.validateFields((err, values) => {
        if (err) {
          return
        }
        console.log(values)
        let formData = new FormData()
        for (let key in values) {
          let value = values[key]
          if (value) formData.append(key, value.file ? value.file : value)
        }
        formData.append('classifyIds[]', classifyIds)
        this.confirmLoading = true
        let pageNum = formData.get('id') ? this.pagination.current : 1
        serv.save(formData).then(res => {
          this.confirmLoading = false
          if (res.data.code === 0) {
            form.resetFields()
            this.visible = false
            this.record = {}
            this.fetch({
              size: this.pagination.pageSize,
              page: pageNum,
              ...this.searchData
            })
          } else {
            this.$message.error(res.data.msg)
          }
        })
      })
    },
    handleCancel (e) {
      this.record = {}
      this.visible = false
    },
    handleOkForBatch (classifyIds, fileList) {
      const form = this.$refs.collectionFormForBatch.form
      form.validateFields((err, values) => {
        if (err) {
          return
        }
        console.log(values)
        let formData = new FormData()
        for (let key in values) {
          let value = values[key]
          if (value) formData.append(key, value.file ? value.file : value)
        }
        for (let key in fileList) {
          let value = fileList[key]
          if (value) formData.append(key, value)
        }
        formData.append('classifyIds[]', classifyIds)
        this.confirmLoadingForBatch = true
        serv.saveForBatch(formData).then(res => {
          this.confirmLoadingForBatch = false
          if (res.data.code === 0) {
            form.resetFields()
            this.visibleForBatch = false
            this.record = {}
            this.fetch({
              size: this.pagination.pageSize,
              page: 1
            })
          } else {
            this.$message.error(res.data.msg)
          }
        })
      })
    },
    handleCancelForBatch (e) {
      this.record = {}
      this.visibleForBatch = false
    },
    async getTree () {
      this.treeData = await serv.getTree()
    },
    onChangeCategoryTree (value) {
      console.log(value)
      if (value) {
        this.searchData.classifyId = value
      } else {
        delete this.searchData.classifyId
      }
      this.searchData = {...this.searchData}
      this.pagination.current = 1
      this.fetch({
        size: this.pagination.pageSize,
        page: this.pagination.current,
        ...this.searchData
      })
    },
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    handleTableChange (pagination, filters, sorter) {
      const pager = { ...this.pagination }
      pager.current = pagination.current
      this.pagination = pager
      this.fetch({
        size: pagination.pageSize,
        page: pagination.current,
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...filters,
        ...this.searchData
      })
    },
    async fetch (params = {}) {
      console.log(params)
      this.loading = true
      this.page = await serv.getPage(params)
      const pagination = { ...this.pagination }
      pagination.total = this.page.totalElements
      // pagination.current = this.page.pageable.pageNumber + 1
      this.loading = false
      this.selectedRowKeys = []
      this.data = this.page.content
      this.pagination = pagination
    }
  }
}
</script>

<style scoped>
.root-table {
  height: 100%;
}
.table-operations {
  margin-bottom: 16px;
}

.table-operations > button {
  margin-right: 8px;
}

.a-col {
  padding: 0 20px;
}

.record-picture {
  max-width: 64px;
  max-height: 40px;
}
</style>
